package com.parachutes.aspbillcore.serivce.impl;
import java.util.Date;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.parachutes.aspbillapi.domain.BusOrder;
import com.parachutes.aspbillapi.domain.Result;
import com.parachutes.aspbillapi.domain.SysWithdrawalRecord;
import com.parachutes.aspbillapi.service.BusOrderService;
import com.parachutes.aspbillapi.service.PaymentService;
import com.parachutes.aspbillcore.mapper.SysWithdrawalRecordMapper;
import com.parachutes.aspsystemapi.domian.SysUser;
import com.parachutes.aspsystemapi.feign.SysUserServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    BusOrderService busOrderService;
    @Autowired
    AlipayConfig alipayConfig;
    @Autowired
    SysUserServiceFeign sysUserServiceFeign;
    @Autowired
    private SysWithdrawalRecordMapper sysWithdrawalRecordMapper;

    @Override
    public Result pay(BusOrder busOrder) {
        {
            String outTradeNo = busOrder.getOutTradeNo();
            com.parachutes.aspsystemapi.domian.Result<SysUser> user = sysUserServiceFeign.getUser(busOrder.getUserId());
            if (!user.isFlag()) {
                throw new IllegalArgumentException("用户不存在");
            }
            // 扣款
            user.getData().setBalance(String.valueOf(Double.parseDouble(user.getData().getBalance()) + Double.parseDouble(busOrder.getTotalAmount())));
            sysUserServiceFeign.updateUser(user.getData());
            busOrder = busOrderService.getOne(Wrappers.lambdaQuery(BusOrder.class).eq(BusOrder::getOutTradeNo, outTradeNo)
                    .eq(BusOrder::getStatus, 0).eq(BusOrder::getUserId, busOrder.getUserId()));
            if (busOrder == null) {
                throw new IllegalArgumentException("订单不存在");
            }
            // 初始化SDK
            AlipayClient alipayClient = null;
            try {
                alipayClient = new DefaultAlipayClient(alipayConfig);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            // 构造请求参数以调用接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            // 设置商户订单号
            model.setOutTradeNo(busOrder.getOutTradeNo());

            // 设置订单总金额
            model.setTotalAmount(busOrder.getTotalAmount());

            // 设置订单标题
            model.setSubject(busOrder.getSubject());

            // 设置产品码
            model.setProductCode("FAST_INSTANT_TRADE_PAY");

            // 设置PC扫码支付的方式
            model.setQrPayMode("1");

            // 设置商户自定义二维码宽度
            model.setQrcodeWidth(100L);

            request.setBizModel(model);

            request.setNotifyUrl("https://5048-223-104-77-158.ngrok-free.app /bill/notify");

            AlipayTradePagePayResponse response = null;
            try {
                response = alipayClient.pageExecute(request, "POST");
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }

            String pageRedirectionData = response.getBody();

            if (response.isSuccess()) {
                // 记录提现记录
                SysWithdrawalRecord sysWithdrawalRecord = new SysWithdrawalRecord();

                sysWithdrawalRecord.setUserId(busOrder.getUserId());
                sysWithdrawalRecord.setMoney(Double.parseDouble(busOrder.getTotalAmount()) * 100);
                sysWithdrawalRecord.setTime(new Date());
                sysWithdrawalRecord.setType("recharge");
                sysWithdrawalRecordMapper.insert(sysWithdrawalRecord);
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
            return Result.of(true, "支付成功", pageRedirectionData);
        }
    }

    @Override
    public void transfer(BusOrder busOrder) {
        busOrder = busOrderService.getOne(
                Wrappers.lambdaQuery(BusOrder.class).eq(BusOrder::getOutTradeNo, busOrder.getOutTradeNo()));
        if (busOrder == null){
            throw new IllegalArgumentException("订单不存在");
        }
        // 初始化SDK
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        // 构造请求参数以调用接口
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();

        // 设置商家侧唯一订单号
        model.setOutBizNo(busOrder.getOutTradeNo());

        // 设置订单总金额
        model.setTransAmount(busOrder.getTotalAmount());

        // 设置描述特定的业务场景
        model.setBizScene("DIRECT_TRANSFER");

        // 设置业务产品码
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");

        // 设置转账业务的标题
        model.setOrderTitle(busOrder.getSubject());

        // 设置收款方信息
        Participant payeeInfo = new Participant();
        com.parachutes.aspsystemapi.domian.Result<SysUser> user = sysUserServiceFeign.getUser(busOrder.getUserId());
        if (!user.isFlag()) {
            throw new IllegalArgumentException("用户不存在");
        }
        SysUser data = user.getData();
        data.setWithdrawal(String.valueOf(Double.parseDouble(data.getWithdrawal()) - Double.parseDouble(busOrder.getTotalAmount())));

        sysUserServiceFeign.updateUser(data);
        payeeInfo.setIdentity(data.getAlipayIdentify());
        payeeInfo.setName(data.getAlipayName());
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        model.setPayeeInfo(payeeInfo);

        // 设置业务备注
        model.setRemark("广州深圳降落伞科技有限公司-代发");

        request.setBizModel(model);
        AlipayFundTransUniTransferResponse response = null;
        try {
            response = alipayClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            // 记录提现记录
            SysWithdrawalRecord sysWithdrawalRecord = new SysWithdrawalRecord();

            sysWithdrawalRecord.setUserId(busOrder.getUserId());
            sysWithdrawalRecord.setMoney(Double.parseDouble(busOrder.getTotalAmount()) * 100);
            sysWithdrawalRecord.setTime(new Date());
            sysWithdrawalRecord.setType("withdrawal");
            sysWithdrawalRecordMapper.insert(sysWithdrawalRecord);
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");

        }
    }

}
